<?php

namespace App\Http\Controllers\Web\V1;

use App\Events\ExamedEvent;
use App\Events\ExamingEvent;
use App\Models\Examination;
use BeyondCode\LaravelWebSockets\WebSockets\Messages\PusherMessageFactory;
use BeyondCode\LaravelWebSockets\WebSockets\WebSocketHandler as BaseWebSocketHandler;
use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;

class WebsocketHandler extends BaseWebSocketHandler
{
    public function onMessage(ConnectionInterface $connection, MessageInterface $message)
    {
        // 获取数据
        $data = json_decode($message->getPayload(), true);

        // 获取考场id
        $key = $this->getQuestionId($data['data']);

        $exam = Examination::query()->find($key);


        if ($exam) {
            if ($exam->status != 1) {
                // 结束事件
                event(new ExamedEvent($key, $exam));
            } else {
                event(new ExamingEvent($key, $data, $exam));
            }

        }


        $message = PusherMessageFactory::createForMessage($message, $connection, $this->channelManager);

        $message->respond();
    }

    /**
     * 获取考场id
     *
     * @param $data
     * @return string
     */
    public function getQuestionId($data)
    {
        static $key = '';
        if (array_key_exists('channel', $data)) {
            $channel = $data['channel'];
            $key = str_replace('private-exam.', '', $channel);
//            $key = str_replace('exam.', '', $channel);
        }

        return $key;
    }

    public function onClose(ConnectionInterface $connection)
    {
        $this->channelManager->removeFromAllChannels($connection);
    }
}
